<template>
  <div class="app-container pb-160" v-cloak>
    <div class="shop-container">
      <h3>商品信息</h3>
      <span v-if="(ruleForm.replaceDeliveryTime == 1) ? true : false" class="timecolor" style="width: 86%;font-size: 20px;">更换配送时间</span>
      <nav v-loading="detailLoading">
        <li
          v-for="(detail,index) in shoplist"
          :key="index"
        >
          <span v-if="detail.productionState == 6 ? true : false" class="timecolor">此蛋糕无货，请联系用户更换蛋糕</span>
          <span v-if="detail.refundNotReturn === '退款不退货' ? true : false" class="timecolor">退款不退货</span>
          <span v-if="ruleForm.refundMark === '平台退款中' ? true : false" class="timecolor">平台退款中</span>
          <p style="display: flex;justify-content: space-between">
            <span><strong class="title-noEdit">蛋糕：</strong>{{ detail.goodsName }}</span>
          </p>
          <p><span><strong class="title-noEdit">规格：</strong>
              <span v-if="detail.goodsSpecsFlags !== true ? true : false">{{ detail.goodsSpecs }}</span>
              <el-input v-show="((ruleForm.status == 1) && (detail.goodsSpecsFlags == true)) ? true : false" v-model.trim="detail.goodsSpecs" clearable maxlength="20" size="medium" style="width: 35%"></el-input>
            </span>
          </p>
          <p><span><strong class="title-noEdit">Sku码：</strong>
              <span v-if="ruleForm.status !== 1 ? true : false">{{ detail.skuCode }}</span>
              <el-input v-show="ruleForm.status == 1 ? true : false" v-model="detail.skuCode" clearable onkeyup="value=value.replace(/[^\-?\d.]/g,'').slice(0,20)" maxlength="20" onafterpaste="value=value.replace(/[^\-?\d.]/g,'').slice(0,20)" size="medium" style="width: 35%"></el-input>
            </span>
          </p>
          <p>
            <span><strong class="title-noEdit">价格：</strong>{{ (detail.totalPrice/100).toFixed(2) }}元</span>
          </p>
          <p>
            <span><strong class="title-noEdit">数量：</strong>{{detail.num}}</span>
          </p>
          <p><span><strong class="title-noEdit">状态：</strong>{{detail.productionStateName}}</span></p>
          <p>
            <span>
              <strong class="title-noEdit">商品类别：</strong>
              <strong
                v-if="ruleForm.status !== 1 ? true : false"
              >
                {{detail.goodsTypeName}}-{{ detail.minGoodsTypeName }}
              </strong>
            </span>
            <el-cascader v-if="ruleForm.status == 1 ? true : false" v-model="detail.categoryIdArray" clearable :placeholder="`${detail.goodsTypeName}-${detail.minGoodsTypeName}`" :options="getCategoriesList" @change="selectCategory(detail.categoryIdArray,index)"></el-cascader>
          </p>
          <p>
            <span class="p-r"><strong class="title-noEdit">祝福语：</strong>
              <el-input type="textarea" class="orderspecial" v-model.trim="detail.blessings" show-word-limit autosize clearable size="medium" style="width: 45%"></el-input>
              <span v-if="detail.blessings && detail.blessings.length" class="c-999 p-a r-10 b-4 fz-12">{{ detail.blessings.length }}</span>
            </span>
          </p>
        </li>
      </nav>
      <div class="EditCake">
        <el-button v-if="canEditGoods" type="primary" @click="openEditCake" >编辑商品</el-button>
      </div>
    </div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <div class="payment-container">
        <h3>支付</h3>
        <el-form-item label="在线支付" prop="totalPrice">
          <el-input v-model.trim="ruleForm.totalPrice" maxlength="9" oninput="value=value.replace(/[^\d.]/g,'')" placeholder="请填写价格" clearable size="medium" :disabled="!canEditPay"></el-input>
          <span style="margin-left: 15px;">元</span>
        </el-form-item>
      </div>
      <div class="channel-container">
        <h3>渠道</h3>
        <el-form-item label="渠道类别" prop="channelType">
          <el-select v-model.trim="ruleForm.channelType" @keydown.native="channelFilter" size="medium" filterable placeholder="渠道类别" :disabled="!canEditChannel">
            <el-option
              v-for="(channelitem,channel) in channelTypellist"
              :key="channel"
              :label="channelitem.channelName"
              :value="channelitem.channelKey"
            >
              <span
                :data-id="channelitem.id"
                :data-channelName="channelitem.channelKey"
                style="display: block;width: 100%;padding: 0 20px;margin-left: -20px;"
                @click="getchannelTypeId($event)"
              >{{ channelitem.channelName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" prop="channel">
          <el-select v-model.trim="ruleForm.channelName" @change="getChannel" @keydown.native="channelFilter" size="medium" filterable placeholder="渠道" :disabled="!canEditChannel">
            <el-option
              v-for="(channelitem,channel) in channerllist"
              :key="channel"
              :label="channelitem.channelName"
              :value="{value:channelitem.channelKey,label:channelitem.channelName}"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="detail-container">
        <h3>订单信息</h3>
        <el-form-item label="后台单号" prop="xmbzNo">
          <el-col>{{ruleForm.xmbzNo}}</el-col>
        </el-form-item>
        <el-form-item label="平台单号">
          <el-input v-model.trim="ruleForm.platformOrderId" :disabled="pageType === 'replenishCopy'" :clearable="pageType === 'copy'" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model.trim="ruleForm.receiverName" maxlength="10" onkeyup="value=value.replace(/\s+/g, '')" onafterpaste="value=value.replace(/\s+/g, '')" show-word-limit clearable size="medium"></el-input>
        </el-form-item>
        <el-form-item label="收货人电话" prop="receiverPhone">
          <el-input type="text" v-model.trim="ruleForm.receiverPhone" maxlength="50" @input="filterPhone" show-word-limit autosize clearable size="medium"></el-input>
        </el-form-item>
        <el-form-item label="下单电话" prop="bookerPhone">
          <el-input type="text" v-model.trim="ruleForm.bookerPhone" maxlength="50" show-word-limit autosize clearable size="medium"></el-input>
        </el-form-item>
        <el-form-item label="订制商品" v-if="showCustomMade" prop="diyCakeName">
          <diyCakeInfo ref="diyCakeInfo" @diyChange="handleDiyChange"></diyCakeInfo>
          
        </el-form-item>
        <el-form-item label="客户备注" prop="customerNotes">
          <el-input class="orderspecial" v-model="ruleForm.customerNotes" type="textarea" maxlength="50" @input="filterSpace('customerNotes')" show-word-limit autosize clearable size="medium"></el-input>
        </el-form-item>
        <el-form-item label="生产备注" prop="productionNotes">
          <el-input v-model="ruleForm.productionNotes" type="textarea" maxlength="100" @input="filterSpace('productionNotes')" show-word-limit autosize clearable size="medium"></el-input>
        </el-form-item>
        <el-form-item label="配送备注" prop="deliveryNotes">
          <el-input v-model="ruleForm.deliveryNotes" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}" type="textarea" maxlength="200" @input="filterSpace('deliveryNotes')" show-word-limit autosize clearable size="medium"></el-input>
        </el-form-item>
        <el-form-item label="客服备注" prop="customerServiceNotes">
          <el-input v-model="ruleForm.customerServiceNotes" type="textarea" maxlength="200" @input="filterSpace('customerServiceNotes')" show-word-limit autosize clearable size="medium"></el-input>
        </el-form-item>
        <el-form-item v-if="ruleForm.groupBuyQRCode ? true : false" label="团购二维码" prop="groupBuyQRCode">
          <img :src="ruleForm.groupBuyQRCode" alt="" style="width: 450px;height: 450px;">
        </el-form-item>
      </div>
      <div class="address-container">
        <h3>配送地址和时间</h3>
        <el-form-item label="配送时间" prop="deliveryStartTime" class="deliveryTimeStyle">
          <el-col v-if="(ruleForm.deliveryStartTime && ruleForm.deliveryEndTime)">客户备注时间：
            {{ ruleForm.deliveryStartTime.slice(5, 16) }}~{{ ruleForm.deliveryEndTime.slice(11, 16) }}</el-col>
          <div style="display: flex;margin-left: -10px;">
            <el-date-picker
              type="date"
              size="medium"
              :placeholder="getdelOrderStartTime"
              v-model="getdeliveryStartTime"
              :picker-options="pickerOptionsStart"
              :clearable="false"
              value-format="yyyy-MM-dd "
              format="yyyy-MM-dd "
              style="width: 170px;margin: 0 0 0 10px;"
            ></el-date-picker>
            <div class="line" :span="1" style="margin:  0 10px;">-</div>
            <selecttime
              ref="getdeliveryTime"
              v-bind:deliveryTime="getdeliveryStartTime"
              v-bind:OrderStartTime="ruleForm.deliveryStartTime"
              v-bind:OrderEndTime="ruleForm.deliveryEndTime"
              style="width: 170px;margin: 0"
            ></selecttime>
          </div>
        </el-form-item>
        <el-form-item label="仓库" class="house-style">
          <el-select v-model="deptName" placeholder="城市" size="small" style="width: 130px;" @change="cityclick">
            <el-option v-for="(house,citykey) in cityselect" :key="citykey" :label="house.deptName" :value="{value:house.id,label:house.deptName}"></el-option>
          </el-select>
          <el-select v-model="ruleForm.mainWarehouse" placeholder="仓库" size="medium" style="width: 280px;margin-left: 5px;">
            <el-option
              v-for="(house,ware) in citylist"
              :key="ware"
              :label="house.deptName"
              :value="house.deptName"
            >
              <span
                :data-id="house.id"
                style="display: block;width: 100%;padding: 0 20px;margin-left: -20px;"
                @click="wareclick($event)"
              >{{ house.deptName }}</span>
            </el-option>
          </el-select>
          <el-select v-model="ruleForm.branchWarehouse" placeholder="仓库" size="medium" style="width: 200px;margin-left: 5px;">
            <el-option v-for="(house,ware) in abbrlist" :key="ware" :label="house.name" :value="house.name">
              <span :data-warehouseId="house.id" @click="getwarehouseId(house.id)" style="display: inline-block;width: 200px;padding: 0 20px;margin-left: -20px;">{{ house.name }}</span>
            </el-option>
          </el-select>
          <!-- 新添加的内容  06:22-->
          <el-popover
            style="margin-left: 20px;"
            class="warehouse"
            placement="right-end"
            width="200"
            v-model="isWarehouse"
            trigger="click">
           <el-select
            v-model="warehouseValue"
            placeholder="请选择仓库"
            @change="getwarehouseValue"
              filterable
            >
              <el-option-group
                v-for="group in options"
                :key="group.label"
                :label="group.label"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :value="item.value">
                </el-option>
              </el-option-group>
            </el-select>
          </el-popover>
        </el-form-item>
        <div>
          <el-form-item label="定位" class="getAddress deletePadding" v-clickoutside="onClickSearchOutside">
            <el-input
              type="textarea"
              id="getDetail"
              ref="search"
              placeholder="请输入地址"
              @keyup.up.native="selectTopItem()"
              @keyup.down.native="selectBottomItem()"
              @keydown.enter.native="getlnglat(currentIndex)"
              v-model="receiverDetailAddress"
              clearable
              size="medium"
              @focus="SearchAddress"
              @input="SearchAddress"
              maxlength="54"
              onkeyup="value=value.replace(/\s+/g, '')"
              onafterpaste="value=value.replace(/\s+/g, '')"
              show-word-limit
              autosize
              style="width: 480px;"
            ></el-input>
            <div class="adressDetailDivCopy" id='mapDiv'>
              <ul
                v-show="addressFlagcopy"
                id='mapDiv'
                class="adressDetail"
              >
                <li
                  id='mapDiv'
                  v-for="(addressitem,index) in addressList.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                  :key="index"
                  :class="currentIndex == index ? 'addressActive' : ''"
                  @click="getlnglat(index)"
                  @mouseover="changeColor(index)"
                  @mouseout="loseColor(index)"
                >
                  <p id='mapDiv' class="el-icon-location-information">{{ addressitem.name }}</p>
                  <p id='mapDiv' class="el-icon-location-information">地址：<span v-if="addressitem.address.length > 0 ? true : false">{{ addressitem.address }}</span></p>
                  <p id='mapDiv' class="el-icon-location-information">城市：<span v-if="addressitem.district !== ''? true : false">{{ addressitem.district }}</span></p>
                </li>
                <el-pagination
                  id='mapDiv'
                  background
                  :current-page.sync="currentPage"
                  layout="prev, pager, next, sizes, total, jumper"
                  :page-sizes="[5, 10, 15, 20]"
                  :page-size.sync="pagesize"
                  :total="addressList.length"
                  @current-change="handleCurrentChange"
                  @size-change="handleSizeChange"
                  style="margin-top: 5px 0;"
                >
                </el-pagination>
              </ul>
            </div>
          </el-form-item>
          <el-form-item label="地址" prop="receiverAddress">
            <el-input
              id="getDetailAddress"
              type="textarea"
              v-model="ruleForm.receiverAddress"
              onkeyup="value=value.replace(/\s+/g, '')"
              onafterpaste="value=value.replace(/\s+/g, '')"
              placeholder="详细地址"
              maxlength="54"
              clearable
              show-word-limit
              autosize
              size="medium"
              class="deletePadding"
              style="width: 480px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="坐标" prop="longAndLat">
            <el-input
              v-model.trim="ruleForm.longAndLat"
              placeholder="115.781085,36.111883"
              size="medium"
              style="width: 480px"
            ></el-input>
          </el-form-item>
          <XmMap ref="xmMap" style="width: 90%;height: 800px; margin: 0;"></XmMap>
          <el-col class="submit-order">
            <el-button size="medium" type="warning" @click="preservation()" style="margin-right: 20px;">创建订单</el-button>
          </el-col>
        </div>
      </div>
    </el-form>
    <!------------- 编辑商品 --------------  -->
    <editGoodsDialog ref="editGoodsDialog" :ruleForm="ruleForm" @onGoodsSubmit="handleGoodsSumbit"></editGoodsDialog>
    <!-- 图片弹框 -->
    <el-dialog
      title
      :visible.sync="imgFlag"
      center
      :append-to-body="true"
      :lock-scroll="false"
      width="80%"
      z-index="2007"
    >
      <div style="width: 100%;">
        <el-scrollbar class="page-component__scroll">
          <el-col>
            <img :src="ruleForm.groupBuyQRCode" alt="" width="100%" height="100%">
          </el-col>
        </el-scrollbar>
      </div>
    </el-dialog>

    <updateWorkGoodsDialog ref="updateWorkGoodsDialog" @submit="confirmTypeOrder(`创建成功，单号${newXmbzNo}`)"></updateWorkGoodsDialog>
  </div>
</template>

<script>
import {
  orderList, // 查询
  detailList,// 订单详情
  getCategories,// 商品类型列表
  getWarehouseListByCityId, // 为了获取城市的名称
} from '@/api/pending';
import {
  citySelect,// 城市
  getOrderChannelList,// 渠道
  getOrderChannelTypeList, // 渠道类别列表
  getMainWarehouseList, // 获取分仓
  getSeparateWarehouseList, // 获取分仓
  getWarehouseName, // 根据经度纬度，返回分仓总仓名称
  judgeGoodsClose, // 判断当前商品是否关闭
  createOrder,    // 创建订单
} from '@/api/createOrder';
import { getWarehouseList, getWarehouseByType } from "@/api/warehouse";
import { getUrlKey } from '@/util/getUrlKey.js';
import deliveryTime from '@/components/foundorder/deliverytime';
import Pagination from "@/components/Pagination"; // 分页
import selecttime from "@/components/foundorder/selecttime"; // 配送时间组件
import {mapGetters} from "vuex";
import Clickoutside from 'element-ui/src/utils/clickoutside'
import editGoodsDialog from '@/components/order-detail/components/editGoodsDialog'
import { getWarehouseLabel, inputTipThrottle } from '@/util/map'
import diyCakeInfo from '@/components/order/diyCakeInfo'
import updateWorkGoodsDialog from '@/components/order-detail/components/updateWorkGoodsDialog';

export default {
  directives: {
    Clickoutside
  },
  components: {
    deliveryTime,
    Pagination,
    selecttime,
    editGoodsDialog,
    diyCakeInfo,
    updateWorkGoodsDialog,
  },
  data() {
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("号码不能为空"));
      }
      var reg = /^1[3456789]\d{9}$/;
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else if (value.toString().length !== 11) {
          callback(new Error("号码长度应为11位"));
        } else if (!reg.test(value)) {
          callback(new Error("手机号码格式有误"));
        } else {
          callback();
        }
      }, 1000);
    };
    let receiverAddress = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("地址不能为空"));
      } else {
        this.ruleForm.receiverAddress = value.replace(/\s+/g, '');
        callback();
      }
    };
    var checkData = (rule, value, callback) => {
      if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
          this.ruleForm.totalPrice = '';
          callback(new Error('编码不能输入汉字!'));
        } else {
          callback();
        }
      }
      callback();
    };
    // 校验定制信息
    let validateDiyData = (rule, value, callback) => {
      if (this.showCustomMade) {
        const diyData = this.$refs.diyCakeInfo.getDiyData()
        if (!diyData.diyCakeName) {
          callback(new Error("请填写订制商品名称!"));
        }
        if (diyData.diyCakeNum + 0 <= 0) {
          callback(new Error("请填写订制商品数量!"));
        }
        if (
          (diyData.diyCakeName == "定制米数蛋糕" ||
          diyData.diyCakeName == "定制多层蛋糕") &&
         (!diyData.diyCakeMeter)  
        ) {
          callback(new Error("请填写订制商品规格!"));
        }
        callback()
      }
    }
    return {
      pageType: (this.$route.query && this.$route.query.pageType) || 'copy',
      options: [],   // 操作合并数组
      warehouseValue: '', // 操作内容
      isWarehouse: false, // 显示摁钮弹框
      shoplist: '',
      orderId: getUrlKey('id'),
      deptId: getUrlKey('cityId') !== 1 ? getUrlKey('cityId') : '',
      deptName: getUrlKey('deptName') !== '全国' ? getUrlKey('deptName') : '',
      cityselect: "", // 城市获取列表
      ruleForm: {
        totalPrice: '',
        channel: '',
        receiverDetailAddress: '',
        channelType: '',
        // wareHouse: '', // 用来获取分仓的参数
        branchWarehouse: '', // 分仓
        orderDetailRequests: [],
      },
      newXmbzNo: '',
      rules: {
        channelType: [
          { required: true, message: '请选择渠道类型', trigger: 'blur' }
        ],
        channel: [
          { required: true, message: '请选择渠道', trigger: 'blur' }
        ],
        totalPrice: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { validator: checkData, trigger: 'change'}
        ],
        receiverName: [
          { required: true, message: '请输入收货人', trigger: 'blur' }
        ],
        receiverPhone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ],
        mainWarehouse: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        branchWarehouse: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        receiverAddress: [{ required: true, validator: receiverAddress, trigger: "change" }],
        diyCakeName: [
          { required: true, validator: validateDiyData, trigger: "blur" },
        ],
      },
      channerllist: '', //渠道
      addressFlagcopy: false,// 地址列表
      addressList: '',
      currentIndex: '',// 选中对应的索引
      pagesize: 5,
      currentPage: 1,
      detailLoading: true,
      channelTypellist: '', // 渠道类别列表
      getChannelList: { // 渠道列表
        parentId: ''
      },
      citylist: "", // 下单仓库中的总仓
      abbrlist: "", // 分仓
      getMainWarehouseList: {
        parentId: ''
      },
      // 分仓
      getSeparateWarehouseList: {
        deptId: 1
      },
      getWarehouseName: {  // 根据经度纬度，返回分仓总仓名称
        longitude: 1,
        latitude: 2
      },
      // 日期
      pickerOptionsStart: {
        disabledDate: time => {
          let yy = new Date().getFullYear();
          let mm = new Date().getMonth() + 1< 10? "0" + (new Date().getMonth() + 1): (new Date().getMonth() + 1);
          let dd = new Date().getDate();
          let nowHours = new Date().getHours() < 10? "0" + new Date().getHours() : new Date().getHours();
          const nowDate = yy + "-" + mm + "-" + dd + ' ';
          this.nowHours = nowHours
          if(nowDate) {
            if(this.ruleForm.deliveryStartTime === nowDate) {
              // console.log(parseInt(nowHours) + parseInt(1)+':00')
              this.condition = true
            } else {
              this.condition = false
            }
          }
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      judgeGoodsCloseQuery: { // 判断当前商品是否关闭请求
        warehouseId: '', // 仓库id
        skuCode: '', // sku码
      },
      getCategoriesList: [],//商品类型列表
      latitude: '',
      longitude: '',
      latitudeFlag: false,
      orderStatus: '',
      getdeliveryStartTime: '', // 时间
      getdelOrderStartTime: '', //订单时间
      receiverDetailAddress: '', // 详细地址
      imgFlag: false,
      warehouseId: '', // 水库是否为空
      map: '',//地图
    }
  },
  watch: {
    'judgeGoodsCloseQuery.warehouseId'() {
      let noCode = [];
      let cakeArray = [];
      this.shoplist.forEach(item => {
        if(item.skuCode !== '' && item.skuCode !== null && item.skuCode !== undefined){
          console.log('sku')
        } else {
          noCode.push(false)
        }
      })
      if(noCode.indexOf(false) > -1) {
        if(this.warehouseId !== this.ruleForm.warehouseId) {
          this.$message({
            type: 'warning',
            message: 'sku码不能为空'
          })
        }
      } else {
        this.shoplist.forEach(item => {
          this.judgeGoodsCloseQuery.skuCode = item.skuCode;
          judgeGoodsClose(this.judgeGoodsCloseQuery).then(res => {
            if(res.data.code == 200) {
              if(res.data.data == true) {
                cakeArray.push(false)
              }
            }
          })
        })
        if(cakeArray.indexOf(false) > -1) {
          this.$message({
            type: 'warning',
            message: '所选仓库没有生产该蛋糕的原料,请联系用户更换蛋糕'
          })
          this.ruleForm.branchWarehouse = '';
        }
      }
    },
  },
  created() {
    this.getList()
  },
  mounted() {
    // 城市
    citySelect(this.cityLi).then(res => {
      this.cityselect = res.data.data;
    })
    // 渠道类别列表
    this.getOrderChannelTypeList()
    // 商品类型选择
    this.getCategories()
  },
  computed: {
    ...mapGetters(["permission"]),
    // 私人订制
    showCustomMade() {
      return this.shoplist && this.shoplist.some((item) =>
        item.goodsName.includes("私人订制")
      );
    },
    canEditGoods() {
      if (this.pageType === 'replenishCopy') {
        return this.permission['inquiry_replenish_editgoods']
      } else {
        return true
      }
    },
    canEditPay() {
      if (this.pageType === 'replenishCopy') {
        return this.permission['inquiry_replenish_editpay']
      } else {
        return true
      }
    },
    canEditChannel() {
      if (this.pageType === 'replenishCopy') {
        return this.permission['inquiry_replenish_editchannel']
      } else {
        return true
      }
    }
  },
  methods: {
    channelFilter(){
      // 什么方法
    },
    // 处理数据方案
    getwarehouseValue(e){
      this.isWarehouse = false
      this.options.map((item,index)=>{
        item.options.map( (item,index)=>{
          if(item.value == this.warehouseValue){
            this.getSeparateWarehouseList.deptId= item.deptId
            // this.ruleForm.warehouseId // 分仓ID
            getSeparateWarehouseList( {'deptId':item.deptId}).then(res => {
              this.abbrlist = res.data.data
            })
            getWarehouseListByCityId({'cityId':item.id}).then(res=>{
              let name = item.value
              res.data.data.map( (item,index)=>{
                console.log(item)
                if(item.name == name){
                  this.ruleForm.warehouseId = item.id
                  this.ruleForm.mainWarehouse = item.deptName
                }
              })
            })
            this.ruleForm.branchWarehouse = item.value
          }
        })
      })
      this.warehouseValue=''
    },

    // 创建变量方案
    changeselectBtn(data){
      this.options = []
      data.map( (item,index)=>{
        let obj = {}
        obj.label = item.deptName
        obj.options = []
        this.options.push(obj)
      })
      data.map((item,index)=>{
          getSeparateWarehouseList({'deptId':item.id}).then(res=>{
            let arr = []
            let dataNameList = data
            res.data.data.map((item,index)=>{
              let obj = {}
              obj.id = item.cityId
              obj.deptId = item.deptId
              obj.value = item.name
              arr.push(obj)
            })
            this.options[index].options = arr
          })
      })
    },

    getChannel(data) {
      // console.log('data',data)
      if(data) {
        this.ruleForm.channel = data.value
        this.ruleForm.channelName = data.label
      }
    },
    // 渠道类别列表
    getOrderChannelTypeList() {
      return getOrderChannelTypeList().then(res => {
        this.channelTypellist = res.data.data;
      })
    },
    getOrderListParams() {
      const params = {
        deptId: this.ruleForm.deptId || this.deptId, // 城市id
        id: this.orderId,
        StartTime: "",
        EndTime: "",
        channelType: "",
        orderTimeSort: 0, // 下单时间排序
        deliveryTimeSort: 0, // 配送时间排序
        page: 1,
        limit: 10,
        size: 10,
        orderDetailRequests: [],
      }
      return params
    },
    getList() {
      let _this = this;
      this.detailLoading = true;
      detailList({orderId: this.orderId}).then(res => {
        this.shoplist = res.data.data
        this.shoplist.forEach((item, i) => {
          item.platformDetailId = i + new Date().getTime()
          item.categoryIdArray = [];
          if(item.goodsSpecs == '') {
            item.goodsSpecsFlags = true;
          } else {
            item.goodsSpecsFlags = false;
          }
        })
        setTimeout(() => {
          this.detailLoading = false;
        }, 0.5 * 1000);
      })
      orderList(this.getOrderListParams()).then(res => {
        let result = res.data.data.rows[0];
        result.totalPrice = (result.totalPrice/100).toFixed(2);
        this.ruleForm = result;
        // if (this.pageType === 'copy') {
        //   this.ruleForm.platformOrderId = '';
        // }
        // 渠道类别列表
        this.getOrderChannelTypeList().then(() => {
          this.channelTypellist.forEach(item => {
            if(item.channelKey == this.ruleForm.channelType) {
              // 获取渠道
              this.getChannelList.parentId = item.id;
              // 渠道列表接口
              getOrderChannelList(this.getChannelList).then(res => {
                this.channerllist = res.data.data;
              })
            }
          })
        })
        this.warehouseId = result.warehouseId || '';
        this.orderStatus = result.status;
        this.receiverDetailAddress = result.receiverAddress || '';
        this.deptId = result.deptId;
        this.getdelOrderStartTime = result.deliveryStartTime.slice(0, 11);
        if(this.getdelOrderStartTime !== '') this.getdeliveryStartTime = this.getdelOrderStartTime;
        this.$refs.diyCakeInfo && this.$refs.diyCakeInfo.setDiyData({
          diyCakeName: result.diyCakeName,
          diyCakeNum: result.diyCakeNum,
          diyCakeMeter: result.diyCakeMeter,
        })

        // 获取总仓
        this.getMainWarehouse(this.ruleForm.deptId)
        this.handleMapData()
        this.judgeOnHouseRange()
      })
    },
    // 获取分仓id
    getwarehouseId(val) {
      this.ruleForm.warehouseId = val
      this.judgeGoodsCloseQuery.warehouseId = val // 判断当前商品是否关闭请求仓库id
    },
    // 下单仓库城市获取
    cityclick(data) {
      if(data){
        this.deptName=data.label;
        this.ruleForm.deptId=data.value;
        this.ruleForm.deptName = data.label
      }
      this.latitudeFlag = false;
      this.startArea(data.value);
      this.handleMapData();
    },
    startArea(datacity) {
      this.getMainWarehouseList.parentId = datacity;
      if (!this.latitudeFlag) {
        // 总仓
        getMainWarehouseList(this.getMainWarehouseList).then((res) => {
          let abbrResult = res.data.data;
          if (abbrResult.length > 0) {
            abbrResult.forEach((item) => {
              if (item.name == this.ruleForm.mainWarehouse) {
                this.ruleForm.mainWarehouse = item.name;
                this.citylist = abbrResult;
              } else {
                this.citylist = abbrResult;
                this.ruleForm.mainWarehouse = "";
                this.ruleForm.branchWarehouse = "";
              }
            });
          }
          this.changeselectBtn(abbrResult);
        });
      }
    },
    // 创建订单
    preservation() {
      const errorMsg = this.validateParams()
      if (errorMsg) {
        this.$confirm(errorMsg, "提示", {
          showCancelButton: false,
          confirmButtonText: "确定",
          type: "warning",
        })
        return
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const params = this.getParams()
          createOrder(params).then(res=>{
            const resData = res.data.data.data || {}
            this.newXmbzNo = resData.xmbzNo
            if(res.data.data.code == 200){
              if (resData && resData.skuModifyId && this.pageType === 'replenishCopy') {
                this.$refs.updateWorkGoodsDialog.show({workOrderId: resData.skuModifyId, orderData: {id: resData.orderId}, source: 1})
              } else {
                this.confirmTypeOrder(`创建成功！后台单号：${this.newXmbzNo}`)
              }
            } else {
              this.$message({
                message: '创建失败！',
                type: 'error'
              })
            }
          })
        } else {
          this.$confirm('还有信息未填完整，请补充完整?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        }
      })
    },
    confirmTypeOrder(message) {
      this.$alert(message, '提示', {
        confirmButtonText: '确定',
        callback: action => {
            window.close();
        }
      })
    },
    getParams() {
      const params = {
        ...this.ruleForm,
        totalPrice: Number(this.ruleForm.totalPrice) * 100,
        receiverAddress: this.receiverDetailAddress,
        deliveryStartTime: `${this.$refs.getdeliveryTime.deliveryTime}${this.$refs.getdeliveryTime.getStartTime()}`,
        deliveryEndTime: `${this.$refs.getdeliveryTime.deliveryTime}${this.$refs.getdeliveryTime.getEndTime()}`,
        orderDetailList: this.shoplist.filter(item => {
          return ['配件', '服务费', '定制蛋糕', '增值服务'].every(name => name != item.goodsTypeName)
        }) || [],
        partsList: this.shoplist.filter(item => item.goodsTypeName == '配件' || item.goodsTypeName == '增值服务') || [],
        serviceClassList: this.shoplist.filter(item => item.goodsTypeName == '服务费') || [],
        workOrderProvisionsList: [],
        customizedOrderDetailList: this.shoplist.filter(item => item.goodsTypeName == '定制蛋糕') || [],
      }
      if (this.pageType === 'copy') {
        params.originalOrderId = this.ruleForm.id || undefined
        params.originalXmbzNo = this.ruleForm.xmbzNo || undefined
      } else if(this.pageType === 'replenishCopy') {
        params.originalReplacementId = this.ruleForm.id
        params.originalReplacementXmbzNo = this.ruleForm.xmbzNo
        params.delivery = ''
        params.receivedTime = ''
      }
      if (this.showCustomMade) {
        const diyData = this.$refs.diyCakeInfo.getDiyData()
        params.diyCakeName = diyData.diyCakeName
        params.diyCakeNum = diyData.diyCakeNum
        params.diyCakeMeter = diyData.diyCakeMeter
      }
      if (this.ruleForm.longAndLat) {
        const location = this.ruleForm.longAndLat.split(',')
        params.longitude = location[0]
        params.latitude = location[1]
        delete params.longAndLat
      }
      return params
    },
    validateParams() {
      const isBlessingsOverLimit = this.shoplist.some(item => item.blessings && item.blessings.length > 32)
      if (isBlessingsOverLimit && !this.UnsubscribeFlag && !this.refundFlag) {
        const overLimitCakes = this.shoplist.filter(item => item.blessings && item.blessings.length > 32)
        return `蛋糕（${overLimitCakes.map(item => item.goodsName).join(',')}）祝福语超过32个字`
      }
    },
    // 地图事件
    SearchAddress() {
      this.addressFlagcopy = true;
      const citySelected = this.cityselect.find(item => this.ruleForm.deptId == item.id)
      inputTipThrottle({
        city: citySelected.deptName,
        keyword: this.receiverDetailAddress
      }).then(res => {
        this.addressList = res.map(item => {
          return {
            ...item,
            lng: item.location && item.location.lng,
            lat: item.location && item.location.lat,
          }
        }).sort((a,b) => {
          // 当前城市排在前面
          return a.district.indexOf(this.ruleForm.deptName) > 1 && b.district.indexOf(this.ruleForm.deptName) == -1 ? -1 : 1
        });
      })
    },
    // 点击地图的列表获取经纬度
    getlnglat(index) {
      this.addressFlagcopy = false;
      index = (this.currentPage - 1) * this.pagesize + index;
      if((typeof index) === 'string') index = 0;
      let pois = this.addressList[index];
      if(pois.lat !== undefined) {
        // console.log('ooooooooooooo')
        this.getWarehouseName.latitude = pois.lat
        this.getWarehouseName.longitude = pois.lng
        this.latitude = pois.lat
        this.longitude = pois.lng
        getWarehouseName(this.getWarehouseName).then(res => {
          if(res.data.msg == '操作成功') {
            this.getSeparateWarehouseList.deptId = res.data.data.deptId;
            this.ruleForm.mainWarehouseId = res.data.data.deptId;
            this.deptName = res.data.data.cityName
            this.ruleForm.deptId = res.data.data.cityId; ////////
            this.ruleForm.mainWarehouse = res.data.data.deptName; ///////
            this.ruleForm.warehouseId = res.data.data.id; /////////
            this.ruleForm.branchWarehouse = res.data.data.name; ////////
            this.judgeGoodsCloseQuery.warehouseId = res.data.data.id // 判断当前商品是否关闭请求仓库id
            if((typeof this.getSeparateWarehouseList.deptId) === 'number') {
              getSeparateWarehouseList(this.getSeparateWarehouseList).then(res => {
                this.abbrlist = res.data.data;
              })
            }
            if(this.deptId == res.data.data.cityId) {
              // console.log('res.data.data没有更换城市',res.data.data)
              // this.ruleForm.receiverAddress = pois.name;
              this.receiverDetailAddress = pois.name;
              this.ruleForm.latitude = pois.lat;
              this.ruleForm.longitude = pois.lng;
              this.latitudeFlag = 'initialcity';
              this.startArea(res.data.data.cityId);
              this.handleMapData();
            } else {
              // console.log('this.deptId',this.deptId)
              this.$confirm('已修改配送城市，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.latitudeFlag = true;
                this.ruleForm.deptName = res.data.data.cityName;
                // this.ruleForm.receiverAddress = pois.name;
                this.receiverDetailAddress = pois.name;
                this.ruleForm.latitude = pois.lat;
                this.ruleForm.longitude = pois.lng;
                this.startArea(res.data.data.cityId);
                this.handleMapData();
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消选择地址'
                })
              })
            }
          } else if (res.data.msg == '暂无承载数据') {
            this.$confirm('您选择的地址不在配送范围内, 请联系用户！', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // this.ruleForm.receiverAddress = pois.name;
              this.receiverDetailAddress = pois.name;
              this.ruleForm.latitude = pois.lat;
              this.ruleForm.longitude = pois.lng;
              this.startArea(this.deptId);
              this.handleMapData();
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消选择地址'
              })
            })
          }
        })
      } else {
        this.$confirm('此地址不存在, 请重新选址！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'warning',
            message: '请继续选择地址!'
          });
          // this.ruleForm.receiverAddress = ''
          this.receiverDetailAddress = '';
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消选择地址'
          });
        });
      }
    },
    //方向键（向上）
    selectTopItem () {
      if(this.addressList.length > 0 && this.addressList.length <= 5) {
        if (this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1) {
          this.currentIndex--;
        } else {
          this.currentIndex = 0;
        }
        // console.log('上',this.currentIndex)
      } else {
        if (this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1) {
          this.currentIndex--;
        } else {
          this.currentIndex = 0;
        }
      }
    },
    //方向键（向下）
    selectBottomItem (index) {
      if(this.addressList.length > 0 && this.addressList.length <= 5) {
        if (this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1) {
          this.currentIndex++;
        } else {
          this.currentIndex = 0;
        }
      } else {
        // console.log('2',this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1)
        if (this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1) {
          this.currentIndex++;
        } else {
          this.currentIndex = 0;
        }
      }
    },
    // 处理地图元素
    handleMapData() {
      if (this.$refs.xmMap) {
        this.$refs.xmMap.clearMap()
        // 未点击城市时划区域
        if (this.ruleForm.deptId == 1) {
          this.ruleForm.deptId = "";
          this.addLocationMarkerOnMap();
        } else {
          this.addLocationMarkerOnMap();
          this.addWarehouseOnMap();
          this.addPlatformWarehouseOnMap();
        }
        this.$refs.xmMap.setCenter([this.ruleForm.longitude, this.ruleForm.latitude])
      }
    },
    // 判断是否在仓库配送范围
    judgeOnHouseRange() {
      const params = {
        latitude: this.ruleForm.latitude,
        longitude: this.ruleForm.longitude,
      }
      getWarehouseName(params).then((res) => {
        if (res.data.msg == "操作成功") {
          if (
            res.data.data.cityId !== this.ruleForm.deptId &&
            this.ruleForm.status == 1
          ) {
            this.$confirm(
              "您选择的地址不在配送范围内, 请联系用户，确认配送地址！",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
          }
        } else if (
          res.data.msg == "暂无承载数据" &&
          this.ruleForm.status == 1
        ) {
          this.$confirm(
            "您选择的地址不在配送范围内, 请联系用户，确认配送地址！",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
        }
      });
    },
    addLocationMarkerOnMap() {
      const marker = this.$refs.xmMap.createMarker({
        longitude: this.ruleForm.longitude,
        latitude: this.ruleForm.latitude,
        label: {
          content: `<div class='info'>${this.receiverDetailAddress}</div>`
        },
        icon: {
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png'
        },
        zIndex: 50
      })
      this.$refs.xmMap.map.add([marker])
    },
    addWarehouseOnMap() {
      getWarehouseList({ cityId: this.ruleForm.deptId }).then(res => {
        const resData = res.data.data || [];
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });

          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#000",
            strokeWeight: 3,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: "#fff",
            zIndex: 40,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
        }
      })
    },
    addPlatformWarehouseOnMap() {
      getWarehouseByType({
        cityId: this.ruleForm.deptId,
        type: 99,
      }).then(res => {
        const resData = res.data.data || []
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });

          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#FF33FF",
            strokeWeight: 2,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: "#1791fc",
            zIndex: 50,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
        }
      })
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pagesize = size
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    // 划过列表颜色改变
    changeColor(index) {
      this.currentIndex = index;
    },
    // 离开列表颜色改变
    loseColor(index) {
      this.currentIndex = index;
    },
    // 选择渠道类型
    getchannelTypeId(e) {
      // console.log('e.currentTarget.dataset',e.currentTarget.dataset)
      this.ruleForm.channelType = e.currentTarget.dataset.channeltype
      this.getChannelList.parentId = e.currentTarget.dataset.id
      // 渠道列表接口
      getOrderChannelList(this.getChannelList).then(res => {
        let result = res.data.data
        result.forEach(item => {
          if (item.channelKey == this.ruleForm.channel) {
            // console.log('有',item)
            this.channerllist = result;
          } else {
            this.channerllist = result;
            this.ruleForm.channel = '';
            this.ruleForm.channelName = ''
          }
        })
      })
    },
    // 下单仓库城市总仓获取
    getMainWarehouse(deptId) {
      // console.log('result',deptId)
      this.getMainWarehouseList.parentId = deptId;
      // 总仓
      if (this.getMainWarehouseList.parentId !== 1) {
        getMainWarehouseList(this.getMainWarehouseList).then(res => {
          let result = res.data.data;
          // console.log('result',result)
          this.citylist = result;
          this.changeselectBtn(result)
          // console.log('this.citylist',this.citylist)
          result.forEach(item => {
            if(this.ruleForm.mainWarehouse == item.deptName) {
              this.citylist = result;
              // 对应总仓的分仓
              getSeparateWarehouseList( {'deptId':item.id}).then(res => {
                this.abbrlist = res.data.data
              })
            }
          })
        })
      }
    },
    // 下单分仓获取
    wareclick(e) {
      console.log(e.currentTarget.dataset.id)
      // console.log('wareclick',e.currentTarget.dataset)
      this.getSeparateWarehouseList.deptId = e.currentTarget.dataset.id
      this.ruleForm.mainWarehouseId = Number(e.currentTarget.dataset.id);
      getSeparateWarehouseList(this.getSeparateWarehouseList).then(res => {
        let abbrResult = res.data.data;
        // console.log('abbrResult',abbrResult.length)
        if(abbrResult.length > 0) {
          abbrResult.forEach(item => {
            if (item.name == this.ruleForm.branchWarehouse) {
              this.ruleForm.branchWarehouse = item.name;
              this.abbrlist = abbrResult;
            } else if(item.name !== this.ruleForm.branchWarehouse) {
              this.abbrlist = abbrResult;
              this.ruleForm.branchWarehouse = ''
            }
          })
        } else {
          this.abbrlist = abbrResult;
          // console.log('this.abbrlist03',abbrResult)
          this.ruleForm.branchWarehouse = ''
        }
      })
      // console.log('this.ruleForm',this.ruleForm)
    },
    openEditCake() { // 打开蛋糕弹窗
      if (!this.ruleForm.branchWarehouse) {
        this.$message({
          message: "您还未选择仓库，请选择仓库后再添加蛋糕",
          type: "warning",
        });
        return
      }
      this.$refs.editGoodsDialog.show({shoplist: this.shoplist})
    },
    // 蛋糕提交
    handleGoodsSumbit({shoplist, sumPrice}) {
      this.shoplist = shoplist || [];
      this.ruleForm.totalPrice = (sumPrice / 100).toFixed(2);
    },
    // 商品类型列表
    getCategories() {
      getCategories("").then(res => {
        const batchdata = res.data.data;
        const dataValueBatch = batchdata =>
          batchdata.map(
            ({
              id,
              categoryName,
              children
            }) =>
            children ? {
              value: id,
              label: categoryName,
              disabled: categoryName == '未知分组' ? true : false,
              children: dataValueBatch(children)
            } : {
              value: id,
              label: categoryName
            }
          );
        this.getCategoriesList = dataValueBatch(batchdata);
        // console.log('getCategoriesList',this.getCategoriesList)
      })
    },
    //选择蛋糕类型
    selectCategory(selected,index) {
      this.getCategoriesList.forEach(item => {
        if(selected[0] == item.value) {
          this.shoplist[index].parentCategoryId = selected[0];
          this.shoplist[index].categoryId = selected[1];
          this.shoplist[index].goodsTypeName = item.label;
        }
      })
    },
    // 备注空格问题
    filterSpace(data) {
      if(data === 'customerNotes') {
        this.ruleForm.customerNotes = this.ruleForm.customerNotes.replace(/^\s+|\s+$/g, '')
      } else if(data === 'productionNotes') {
        this.ruleForm.productionNotes = this.ruleForm.productionNotes.replace(/^\s+|\s+$/g, '')
      } else if(data === 'deliveryNotes') {
        this.ruleForm.deliveryNotes = this.ruleForm.deliveryNotes.replace(/^\s+|\s+$/g, '');
      } else if(data === 'customerServiceNotes') {
        this.ruleForm.customerServiceNotes = this.ruleForm.customerServiceNotes.replace(/^\s+|\s+$/g, '')
      }
    },
    // 电话号码限制
    filterPhone(val) {
      // console.log('va',val)
      this.ruleForm.receiverPhone = val.replace(/[^\d]/g,'');
    },
    // 定制信息blur
    handleDiyChange(diyInfo) {
      this.ruleForm.productionNotes = this.ruleForm.productionNotes.replace(/【订制信息：([\s\S]+)】/, '') + `【订制信息：${diyInfo}】`
    },
    // 点击地址搜索框以外
    onClickSearchOutside() {
      this.addressFlagcopy = false
    }
  },
  beforeDestroy() {
    if (this.detailtimer) {
      clearInterval(this.detailtimer); // 在Vue实例销毁前，清除我们的定时器
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/orderdetail.scss';
.warehouse{
  .el-button{
    padding: 10px;
    font-size: 12px;
  }
}
.refundcake {
  display: flex;
  flex-wrap: wrap;
}
.refundcakeFlag {
  margin: 15px 10px;
  .el-checkbox {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 15px;
    .el-checkbox__label {
      display: flex;
    }
  }
}
.deliveryTimeStyle {
  .el-form-item__content {
    display: flex;
    flex-direction: column;
  }
}
// 在填充数据之前隐藏
[v-cloak] {
  display: none;
}
</style>
